﻿//signedin user calendars
var calendarIdToSummaryMap;

function getICAL() {

    if (schedulesAsJson[currentRank] == undefined) {
        alert("schedule has no events !!!");
        return;
    }
    var finalICal = "BEGIN:VCALENDAR\nVERSION:2.0";

    var i = 0;
    for (i = 0; i < schedulesAsJson[currentRank].jsTable.length; i++) {
        if (schedulesAsJson[currentRank].jsTable[i].start == "" || schedulesAsJson[currentRank].jsTable[i].duration == 0) {
            continue;
        }
        var eventName = schedulesAsJson[currentRank].jsTable[i].courseName + " - " +
                        schedulesAsJson[currentRank].jsTable[i].groupRole + " " +
                        schedulesAsJson[currentRank].jsTable[i].groupNumber;
        var eventLocation = schedulesAsJson[currentRank].jsTable[i].room;
        var eventDay = schedulesAsJson[currentRank].jsTable[i].day;
        var startTimeSplitted = schedulesAsJson[currentRank].jsTable[i].start.split(".");
        var eventStartTime = startTimeSplitted[0] + startTimeSplitted[1] + "00Z";
        var eventEndTime = calculateEndTime(schedulesAsJson[currentRank].jsTable[i].start,
                                            schedulesAsJson[currentRank].jsTable[i].duration);
        //var id = calendarIdToSummaryMap[0].calendarId;
        eventEndTime = eventEndTime.replace(":", "");
        eventEndTime = eventEndTime.replace(":", "");
        finalICal += "\n" + buildICAL("", eventName, eventLocation, eventDay, eventStartTime, eventEndTime + "Z");
    }
    finalICal += "\nEND:VCALENDAR";
    //var id = calendarIdToSummaryMap[0].calendarId;
    //var summay = calendarIdToSummaryMap[0].symmary;
    //alert("Sync done successfully :)");
    //alert("ICal: " + finalICal);
    download('calendar.ics', finalICal);


}

// syncs with google calendar
function syncWithGoogleCalendar() {
    if (calendarIdToSummaryMap == undefined) {
        alert("to sync with goole calendar you must signin with google account !!!");
        return;
    }
    if (schedulesAsJson[currentRank] == undefined) {
        alert("schedule has no events !!!");
        return;
    }

    var i = 0;
    for (i = 0; i < schedulesAsJson[currentRank].jsTable.length; i++) {
        if (schedulesAsJson[currentRank].jsTable[i].start == "" || schedulesAsJson[currentRank].jsTable[i].duration == 0) {
            continue;
        }
        var eventName = schedulesAsJson[currentRank].jsTable[i].courseName + " - " +
                        schedulesAsJson[currentRank].jsTable[i].groupRole + " " +
                        schedulesAsJson[currentRank].jsTable[i].groupNumber;
        var eventLocation = schedulesAsJson[currentRank].jsTable[i].room;
        var eventDay = schedulesAsJson[currentRank].jsTable[i].day;
        var startTimeSplitted = schedulesAsJson[currentRank].jsTable[i].start.split(".");
        var eventStartTime = startTimeSplitted[0] + ":" + startTimeSplitted[1] + ":00";
        var eventEndTime = calculateEndTime(schedulesAsJson[currentRank].jsTable[i].start,
                                            schedulesAsJson[currentRank].jsTable[i].duration);
        var id = calendarIdToSummaryMap[0].calendarId;
        addEventToCalendar(id, eventName, eventLocation, eventDay, eventStartTime, eventEndTime);
    }
    var id = calendarIdToSummaryMap[0].calendarId;
    var summay = calendarIdToSummaryMap[0].symmary;
    alert("Sync done successfully :)");
}

function calculateEndTime(startTime, duration) {
    var startTimeSplitted = startTime.split(".");
    var hourHalfsSum = 0;
    if (startTimeSplitted[1].toString().indexOf("3") != -1) {
        hourHalfsSum = 0.5;
    }
    var hour = (parseInt(startTimeSplitted[0]) + parseInt(duration) + hourHalfsSum) % 24;
    if (hour.toString().indexOf(".5") != -1) {
        return hour.toString().split(".")[0] + ":30:00";
    } else {
        return hour.toString() + ":00:00";
    }
}

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', "calendar.ics");
    pom.click();
}


// adds an event to the calendar with id  = calendarId.
function addEventToCalendar(calendarId, name, location, day, startTime, endTime) {
    var today = new Date();
    today.setDate(today.getDate() - today.getDay() + parseInt(day));
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();

    if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = yyyy + '-' + mm + '-' + dd + 'T';
    // startTime and endTime must be of the format "2014-02-15T15:30:00"
    var newEvent = {
        "summary": name + " " + location,
        "location": location,
        "start": {
            "dateTime": today + startTime,
            "timeZone": "Israel"
        },
        "end": {
            "dateTime": today + endTime,
            "timeZone": "Israel"
        },
        "recurrence": [
             "RRULE:FREQ=WEEKLY"
        ]
    };
    request = gapi.client.calendar.events.insert({
        'calendarId': calendarId,
        'resource': newEvent
    });
    request.execute(function (resp) {
    });
}

function buildICAL(calendarId, name, location, day, startTime, endTime) {
    var today = new Date();
    today.setDate(today.getDate() - today.getDay() + parseInt(day));
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();

    if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = yyyy + mm + dd + 'T';
    // startTime and endTime must be of the format "2014-02-15T15:30:00"
    //var newEvent = {
    //    "summary": name + " " + location,
    //    "location": location,
    //    "start": {
    //        "dateTime": today + startTime,
    //        "timeZone": "Israel"
    //    },
    //    "end": {
    //        "dateTime": today + endTime,
    //        "timeZone": "Israel"
    //    },
    //    "recurrence": [
    //         "RRULE:FREQ=WEEKLY"
    //    ]
    //};

    var newEvent = "BEGIN:VEVENT\nDTSTART:" + (today + startTime) + "\nDTEND:" + (today + endTime) + "\nSUMMARY:" + (name + " " + location) + "\nLOCATION:" + location + "\nRRULE:FREQ=WEEKLY;COUNT=14";
    newEvent += "\nEND:VEVENT";

    return newEvent;
}

// gets all user's available calendars.   
function getAvailableCalendars() {
    calendarIdToSummaryMap = new Array();
    gapi.client.load('calendar', 'v3', function () {
        // gapi.client.setApiKey('AIzaSyDG2OfoBsulH5kwq3joezD84BEt_6Ukj - c');
        var request = gapi.client.calendar.calendarList.list({});
        request.execute(function (resp) {
            for (var i = 0; i < resp.items.length; i++) {
                var calendarID = resp.items[i].id;
                var calendarSummary = resp.items[i].summary;
                calendarIdToSummaryMap[i] = { "calendarId": calendarID, "summary": calendarSummary };
            }
            //addEventToCalendar(calendarID, "matam", "taub 1", 6, "14:30:00", "15:30:00")
        });
    });
}